// import { reqFeeDay, reqItpkApi } from './service/api'
// const { reqFeeDay, reqItpkApi } = require('./service/api');, '今天冲嘛？！'
const { Wechaty } = require('wechaty');
const schedule = require('./schedule');
const config = require('config');
const axios = require('axios');

let botKey = '@kevin';
let RoomList = ['测试微信机器人', '测试微信机器人2'];

const bot = new Wechaty();

async function onScan(qrcode, status) {
    require('qrcode-terminal').generate(qrcode, { small: true }); // 在console端显示二维码
    const qrcodeImageUrl = [
        'https://api.qrserver.com/v1/create-qr-code/?data=',
        encodeURIComponent(qrcode),
    ].join('');
    console.log(qrcodeImageUrl)
    // let a = await reqItpkApi(' ')
}

// 登录
async function onLogin(user) {
    console.log(`贴心小助理${user.name()}登录了`);
    botKey = `@${user.name()}`
    ///当前聊天列表
    // let users = await bot.Contact.findAll()
    // console.log("获取到的列表", users)
    // ///当前聊天群列表
    // let rooms = await bot.Room.findAll()
    // console.log("获取到的房间列表", rooms)
    // let room = await bot.Room.find({topic:'今天冲嘛？！'});
    // let message = '我收到了消息, 进来看一眼'
    // let res = await room.say(message)
    // console.log('发送消息结果', res)「kevin：检测到群消息! 」<br/>- - - - - - - - - - - - - - -<br/>嗯嗯
}

async function onMessage(msg) {
    let contact = msg.talker();
    // console.log('发送人Id=', contact.id)
    // console.log('发送人name=', contact.name())
    const alias = await contact.alias()
    // console.log('发送人alias=', alias)
    let text = msg.text();
    // console.log('发送的消息', text)
    let room = msg.room();
    // console.log('发送的room', room)
    if (!contact || msg.self()) {
        return;
    }
    if (room) {
        sendRoomMessage(room, text, contact);
    } else {
        // let fromAlias = await contact.alias();
        // console.log('发送的contact=', contact)
        // if (fromAlias === '有脾气的小萝莉') {
        //     let dong = await bot.Contact.find({ alias: fromAlias });
        //     let message = '我收到了消息, 进来看一眼'
        //     let res = await dong.say(message)
        //     console.log('发送消息结果', res)
        // }
        // console.log('alias=', fromAlias)
        // if (text === '我吃过了' && fromAlias === toAlais) {
        // }
    }

}

async function sendRoomMessage(room, text, contact) {
    let message = '检测到群消息! '
    // console.log('群', JSON.stringify(contact))
    let fromTopic = await room.topic();
    let aRoom = await bot.Room.find({ topic: fromTopic });
    if (RoomList.includes(fromTopic)) {
        if (text === message) return
        else if (text.match(RegExp(`${botKey}`))) {
            message = await reqItpkApi(text.replace(botKey, ''))
            let fromAlias = await contact.alias();
            console.log(`机器人回答${fromAlias}=`, message)
            message = `<br/>- - - - - - - - - - - - - - -<br/>${message}`
            // let mention = await bot.Contact.find({ alias: fromAlias });
            if (contact) {
                let res = await aRoom.say(message, contact)
            } else {
                let res = await aRoom.say(message)
            }
            // console.log('发送消息结果', res)
        } else {
            // room.say(`多群同步消息`)
            let topics = RoomList.filter(x => x !== fromTopic)
            topics.map(async topic => {
                let room = await bot.Room.find({ topic: topic });
                room.say(`「${fromTopic}」【${contact.name()}】${text}`)
            })
        }
    }
}

async function reqItpkApi(question) {
    console.log('请求参数', question)
    if (question) question = question.trim()
    if (!question) return '@我干嘛又不说话! '
    question = encodeURIComponent(question)
    let res = await axios.get(`http://i.itpk.cn/api.php?question=${question}&api_key=f63bd0d56230247e90d6741203ead2e6&api_secret=fo6ib70dbt52`)
    // console.log('请求结果', res)
    // return res.data
    return dealItpkResult(res.data)
}

async function dealItpkResult(data) {
    //处理小机器人的返回值
    let message = ''
    if (typeof data === 'string') {
        message = data
    } else if (data.title) {
        message = `${data.title}<br/>${data.content}`
    } else if (data.type === '观音灵签') {
        message = `${data.number1}  ${data.haohua}<br/>签语: ${data.qianyu}<br/>诗意解签: ${data.shiyi}<br/>白话解签: ${data.jieqian}<br/>`
        console.log('观音灵签', message)
    } else if (data.type === '月老灵签') {
        message = `${data.number1}  ${data.haohua}<br/>
        签语: ${data.shiyi}<br/>
        此签的诗意: ${data.jieqian}<br/>
        白话解签: ${data.baihua}<br/>
        `
    } else {
        message = `没有处理的回答${JSON.stringify(data)}`
    }
    return message
}

async function onLogOut(contact, data) {
    console.log(`贴心小助理${contact.name()}登录了`, data);
}

bot.on('scan', onScan);
bot.on('login', onLogin);
bot.on('logout', onLogOut);
bot.on('message', onMessage);

bot.start();


